<template>
  <div class="prediction-results">
    <h2>健康风险预测结果</h2>
    
    <!-- 预测须知弹窗 -->
    <div v-if="showNotice" class="notice-modal-overlay">
      <div class="notice-modal-content">
        <h3>预测须知</h3>
        <p>{{ popupConfig.popupContent }}</p>
        <div class="countdown">
          <span>请阅读以上内容：{{ countdown }}秒</span>
        </div>
        <button :disabled="countdown > 0" @click="closeNotice" class="notice-close-btn">关闭弹窗</button>
      </div>
    </div>
    
    <div class="prediction-card">
      <div class="risk-overview">
        <h3>风险评估</h3>
        <div class="risk-score">
          <div class="score-number">{{ (predictionData.riskValue * 100).toFixed(2) }}%</div>
          <div :class="['risk-level', `risk-${predictionData.riskLevel}`]">
            {{ getRiskLevelText(predictionData.riskLevel) }}
          </div>
        </div>
      </div>
      
      <div class="risk-factors">
        <h3>风险贡献因子</h3>
        <div class="factors-list">
          <div v-for="(factor, index) in predictionData.contributingFactors" :key="index" class="factor-item">
            <span class="factor-name">{{ factor.name }}</span>
            <div class="factor-bar">
              <div class="factor-fill" :style="{ width: factor.percentage.toFixed(2) + '%' }"></div>
            </div>
            <span class="factor-percentage">{{ factor.percentage.toFixed(2) }}%</span>
          </div>
        </div>
      </div>
      
      <div class="improvement-suggestions">
        <h3>个性化改善建议</h3>
        <ul class="suggestions-list">
          <li v-for="(suggestion, index) in predictionData.suggestions" :key="index">
            {{ suggestion }}
          </li>
        </ul>
      </div>
    </div>
    
    <div class="related-info">
      <h3>相关健康知识</h3>
      <div class="knowledge-cards">
        <div class="knowledge-card">
          <h4>心血管健康的重要性</h4>
          <p>心血管疾病是全球范围内的主要死因，保持良好的生活习惯和定期检查可以有效降低风险。</p>
        </div>
        <div class="knowledge-card">
          <h4>健康饮食建议</h4>
          <p>建议减少高脂肪、高盐、高糖食物的摄入，增加蔬果、全谷物、优质蛋白质的比例。</p>
        </div>
        <div class="knowledge-card">
          <h4>适量运动</h4>
          <p>每周至少进行150分钟中等强度的有氧运动，如快走、游泳、骑自行车等。</p>
        </div>
      </div>
    </div>
    
    <div class="action-buttons">
      <router-link to="/user/health-data" class="action-btn">再次录入数据</router-link>
      <router-link to="/user/data-history" class="action-btn">查看历史记录</router-link>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import fastApi from '../../utils/fastApiConfig'
import api from '../../utils/axiosConfig'
import { useUserStore } from '../../stores/user'

export default {
  name: 'PredictionResults',
  setup() {
    const userStore = useUserStore()
    const showNotice = ref(true)
    const countdown = ref(5)
    const loading = ref(false)
    
    // 预测数据，默认提供一些示例数据
    const predictionData = ref({
      riskValue: 0.12,
      riskLevel: 'low', // low, medium, high
      contributingFactors: [
        { name: '年龄因素', percentage: 25 },
        { name: '血压偏高', percentage: 35 },
        { name: '胆固醇偏高', percentage: 25 },
        { name: '缺乏运动', percentage: 15 }
      ],
      suggestions: [
        '体重指数23.5属于正常范围，请继续保持',
        '血压略高于理想值，建议减少盐分摄入，保持规律作息',
        '建议每周进行至少150分钟的有氧运动',
        '保持健康饮食，减少高脂肪食物摄入',
        '定期监测血压和胆固醇水平'
      ]
    })
    
    // 弹窗配置
    const popupConfig = ref({
      popupContent: '本预测基于您的血压、胆固醇等指标计算，结果仅供参考，不能替代医学诊断。建议每年进行一次专业体检。',
      countdownSeconds: 5
    })
    
    // 获取弹窗配置
    const fetchPopupConfig = async () => {
      try {
        const response = await api.get('/popup-config/all')
        if (response.data && response.data.length > 0) {
          // 使用第一个弹窗配置
          popupConfig.value = {
            popupContent: response.data[0].popupContent,
            countdownSeconds: response.data[0].countdownSeconds || 5
          }
          console.log('从后端获取弹窗配置成功:', popupConfig.value)
          // 更新倒计时
          countdown.value = popupConfig.value.countdownSeconds
        }
      } catch (error) {
        console.error('获取弹窗配置失败:', error)
        // 使用默认配置
      }
    }
    
    // 获取预测结果
    const fetchPredictionResult = async () => {
      loading.value = true
      try {
        // 先尝试从localStorage获取最新预测
        const latestPrediction = localStorage.getItem('latestPrediction')
        if (latestPrediction) {
          try {
              const parsedPrediction = JSON.parse(latestPrediction)
              // 处理FastAPI返回的数组格式结果
              if (Array.isArray(parsedPrediction) && parsedPrediction.length > 0) {
                const firstPrediction = parsedPrediction[0];
                // 转换数据结构以匹配前端期望的格式
                predictionData.value = {
                  riskValue: firstPrediction.probability || 0,
                  riskLevel: firstPrediction.probability >= 0.7 ? 'high' : 
                            (firstPrediction.probability >= 0.3 ? 'medium' : 'low'),
                  contributingFactors: [
                    { name: '年龄因素', percentage: 25 },
                    { name: '血压偏高', percentage: 35 },
                    { name: '胆固醇偏高', percentage: 25 },
                    { name: '缺乏运动', percentage: 15 }
                  ],
                  suggestions: [
                    '体重指数正常范围，请继续保持',
                    '血压略高于理想值，建议减少盐分摄入，保持规律作息',
                    '建议每周进行至少150分钟的有氧运动',
                    '保持健康饮食，减少高脂肪食物摄入',
                    '定期监测血压和胆固醇水平'
                  ]
                }
              } else {
                predictionData.value = parsedPrediction
              }
              console.log('从localStorage加载预测结果:', parsedPrediction)
            } catch (parseError) {
            console.error('解析localStorage预测数据失败:', parseError)
            localStorage.removeItem('latestPrediction') // 清除损坏的数据
          }
        } else {
          // 如果localStorage没有，从FastAPI获取最新预测
          const userId = userStore.userInfo.userId || 
                        userStore.userInfo.user_id || 
                        userStore.user_id || 
                        userStore.userId
          
          if (userId) {
            try {
                const response = await fastApi.get(`/predictions/${userId}`)
                let formattedData = response.data
                
                // 处理FastAPI返回的数组格式结果
                if (Array.isArray(response.data) && response.data.length > 0) {
                  const firstPrediction = response.data[0];
                  // 转换数据结构以匹配前端期望的格式
                  formattedData = {
                    riskValue: firstPrediction.probability || 0,
                    riskLevel: firstPrediction.probability >= 0.7 ? 'high' : 
                              (firstPrediction.probability >= 0.3 ? 'medium' : 'low'),
                    contributingFactors: [
                      { name: '年龄因素', percentage: 25 },
                      { name: '血压偏高', percentage: 35 },
                      { name: '胆固醇偏高', percentage: 25 },
                      { name: '缺乏运动', percentage: 15 }
                    ],
                    suggestions: [
                      '体重指数正常范围，请继续保持',
                      '血压略高于理想值，建议减少盐分摄入，保持规律作息',
                      '建议每周进行至少150分钟的有氧运动',
                      '保持健康饮食，减少高脂肪食物摄入',
                      '定期监测血压和胆固醇水平'
                    ]
                  }
                }
                
                predictionData.value = formattedData
                // 保存到localStorage
                localStorage.setItem('latestPrediction', JSON.stringify(response.data)) // 保存原始数据
                console.log('从FastAPI加载预测结果:', response.data)
              } catch (apiError) {
              console.error('从FastAPI获取预测失败:', apiError)
              // 保持使用默认数据
            }
          }
        }
      } catch (error) {
        console.error('获取预测结果失败:', error)
        // 保持使用默认模拟数据
      } finally {
        loading.value = false
      }
    }
    
    onMounted(async () => {
      // 先获取弹窗配置
      await fetchPopupConfig()
      
      // 开始倒计时
      const timer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)
      
      // 获取预测结果
      fetchPredictionResult()
    })
    
    const getRiskLevelText = (level) => {
      switch(level) {
        case 'low': return '低风险'
        case 'medium': return '中风险'
        case 'high': return '高风险'
        default: return '未知风险'
      }
    }
    
    const closeNotice = () => {
      if (countdown.value <= 0) {
        showNotice.value = false
      }
    }
    
    return {
      showNotice,
      countdown,
      popupConfig,
      predictionData,
      loading,
      getRiskLevelText,
      closeNotice
    }
  }
}
</script>

<style scoped>
.prediction-results {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
}

.prediction-results h2 {
  color: #333;
  margin-bottom: 20px;
}

/* 弹窗样式 */
.notice-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}

.notice-modal-content {
  background-color: #fff;
  border-radius: 8px;
  padding: 30px;
  max-width: 500px;
  width: 90%;
  text-align: center;
}

.notice-modal-content h3 {
  color: #333;
  margin-bottom: 20px;
}

.notice-modal-content p {
  color: #606266;
  margin-bottom: 20px;
  line-height: 1.6;
}

.countdown {
  margin-bottom: 20px;
  color: #409eff;
  font-size: 16px;
}

.notice-close-btn {
  padding: 10px 30px;
  background-color: #409eff;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.notice-close-btn:disabled {
  background-color: #c0c4cc;
  cursor: not-allowed;
}

.prediction-card {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 30px;
}

.risk-overview {
  text-align: center;
  margin-bottom: 30px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
}

.risk-overview h3 {
  color: #333;
  margin-bottom: 20px;
}

.score-number {
  font-size: 48px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 10px;
}

.risk-level {
  font-size: 24px;
  font-weight: 500;
}

.risk-low {
  color: #67c23a;
}

.risk-medium {
  color: #e6a23c;
}

.risk-high {
  color: #f56c6c;
}

.risk-factors,
.improvement-suggestions {
  margin-bottom: 30px;
}

.risk-factors h3,
.improvement-suggestions h3 {
  color: #333;
  margin-bottom: 15px;
}

.factors-list {
  background-color: #fff;
  padding: 15px;
  border-radius: 4px;
}

.factor-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.factor-name {
  width: 100px;
  color: #606266;
}

.factor-bar {
  flex: 1;
  height: 20px;
  background-color: #f0f2f5;
  border-radius: 10px;
  margin: 0 15px;
  overflow: hidden;
}

.factor-fill {
  height: 100%;
  background-color: #409eff;
  transition: width 0.5s ease;
}

.factor-percentage {
  width: 50px;
  text-align: right;
  color: #303133;
}

.suggestions-list {
  background-color: #fff;
  padding: 15px 25px;
  border-radius: 4px;
  margin: 0;
}

.suggestions-list li {
  margin-bottom: 8px;
  color: #606266;
  line-height: 1.6;
}

.related-info h3 {
  color: #333;
  margin-bottom: 15px;
}

.knowledge-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.knowledge-card {
  background-color: #f0f9eb;
  border-radius: 8px;
  padding: 20px;
}

.knowledge-card h4 {
  color: #67c23a;
  margin-bottom: 10px;
}

.knowledge-card p {
  color: #606266;
  line-height: 1.6;
}

.action-buttons {
  display: flex;
  gap: 20px;
  justify-content: center;
}

.action-btn {
  padding: 10px 30px;
  background-color: #409eff;
  color: #fff;
  text-decoration: none;
  border-radius: 4px;
  text-align: center;
}

.action-btn:hover {
  background-color: #66b1ff;
}
</style>